#include "CMQTTClient.h"

CMQTTClent::CMQTTClent()
{
	conn_opts = MQTTClient_connectOptions_initializer;
	msg = MQTTClient_message_initializer;
}

CMQTTClent::~CMQTTClent()
{
}

void CMQTTClent::init()
{
	MQTTClient_create(&client, conf.address.c_str(), conf.clientID.c_str(),
		MQTTCLIENT_PERSISTENCE_NONE, NULL);

	conn_opts.keepAliveInterval = conf.keepAliveInterval;
	conn_opts.cleansession = conf.cleanSession;

	MQTTClient_setCallbacks(client, conf.context, conf.connlostCB, conf.msgCB, conf.deliverycompleteCB);

	if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
	{
		printf("Failed to connect, return code %d\n", rc);
		//exit(EXIT_FAILURE);
	}
}

void CMQTTClent::startSub()
{
	MQTTClient_subscribe(client, conf.topic.c_str(), conf.qos);
	//printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
	//	"Press Q<Enter> to quit\n\n", conf.topic.c_str(), conf.clientID.c_str(), conf.qos);
	int ch;
	do
	{
		ch = getchar();
	} while (ch != 'Q' && ch != 'q');
}

int CMQTTClent::publish(char * data, int len, int retained)
{
	msg.payload = data;
	msg.payloadlen = len;
	msg.retained = retained;
	msg.qos = conf.qos;

	int ret = MQTTClient_publishMessage(client, conf.topic.c_str(), &msg, &token);
	printf("The ret of pub:%d\n", ret);
	if (ret == 0)
		return ret;
	while (ret < 0)
	{
		MQTTClient_disconnect(client, 1000);
		this->reconnect();
		ret = MQTTClient_publishMessage(client, conf.topic.c_str(), &msg, &token);
	}
	return ret;
	//MQTTClient_waitForCompletion(client, token, conf.timeout);
}

void CMQTTClent::mqttDestory()
{
	if (conf.type == SUBSCRIBE)
		MQTTClient_unsubscribe(client, conf.topic.c_str());

	MQTTClient_disconnect(client, 1000);
	MQTTClient_destroy(&client);
}

int CMQTTClent::reconnect()
{
	if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
	{
		printf("Failed to reconnect, return code %d\n", rc);
		return -1;
		//exit(EXIT_FAILURE);
	}
	return 1;
}
